package com.tarena.lbs.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.dao.repository.TagRepository;
import com.tarena.lbs.basic.pojo.po.TagLibraryPO;
import com.tarena.lbs.basic.pojo.vo.TagLibraryVO;
import com.tarena.lbs.basic.pojo.vo.TagVO;
import com.tarena.lbs.basic.service.TagService;
import com.tarena.lbs.common.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagRepository  tagRepository;

    @Override
    public Map<String, List<TagVO>> tagMap(Integer tagType) {

    //1.使用tagType 查询某一个类型的标签所有的列表 select * from lbs_tag_library where tag_type=0
    QueryWrapper<TagLibraryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag_type",tagType);
    List<TagLibraryPO> pos = tagRepository.list(queryWrapper);
    //查询出来不分级别的 poList
    //2.Map返回值所需要的数据全部都在poList 用业务封装转化一下数据
    Map<String,List<TagVO>> mapVO=assembleTagMap(pos);
        return mapVO;
}

private Map<String, List<TagVO>> assembleTagMap(List<TagLibraryPO> pos) {
    //1.map需要key 根据key值 封装list
    Map<String,List<TagVO>> mapVO=new HashMap<>();
    //2.遍历pos 筛选pos 先把一级标签筛选出来
    List<TagLibraryPO> firstLevelPos = pos.stream().filter(po -> po.getTagParentId().equals(0)).collect(Collectors.toList());
    //3.循环一级标签
    for (TagLibraryPO firstLevelPo : firstLevelPos) {
        //拿到一级标签名字
        String tagName=firstLevelPo.getTagName();
        //拿到一级标签id
        Integer tagId=firstLevelPo.getId();
        //使用一级标签的id对pos做筛选 拿到该一级标签的下级po列表
        List<TagLibraryPO> secondLevelPos = pos.stream().filter(po -> po.getTagParentId().equals(tagId)).collect(Collectors.toList());
        //使用po的二级标签集合转化TagVo集合
        List<TagVO> vos=
                secondLevelPos.stream().map(po-> {
                            TagVO vo=new TagVO();
                            vo.setTagCategoryName(tagName);
                            TagLibraryVO tagLibraryVO=new TagLibraryVO();
                            BeanUtils.copyProperties(po,tagLibraryVO);
                            vo.setTagLibraryBO(tagLibraryVO);
                            return vo;
                        }
                ).collect(Collectors.toList());
        mapVO.put(tagName,vos);
    }
    return mapVO;
}

}
